#!/usr/bin/Python
import os, sys, random, math, random, pygame, pygame.gfxdraw
from qnd import *
from  pygame.locals import *

FPS = 120.
LMB = 1
RMB = 3
MMB = 2
HUDSIZE = (256,16*6)

def new_tilemap((width,height),defaultTile = 0):
	newtilemap = []
	for i in range(width):
		newtilemap.append(bytearray(height))
	return newtilemap		

def drawHUD(HUDsurface, tileset, paintNumber, data=[], alpha = 180):
	"""Draw the Heads Up Display. Currently mainly for debugging purposes"""
	screenHeight = screen.get_height()
	screenWidth = screen.get_width()
	backcolor = (200,200,200)
	textcolor = (0,0,0)
	HUDsurface.set_alpha(alpha)
	lineHeight = 16
	height = HUDsurface.get_height()
	width = HUDsurface.get_width()
	hudx = 0
	hudy = screenHeight - height

	pygame.draw.rect(HUDsurface, backcolor, (0,0,width,height))
	pygame.draw.rect(HUDsurface, textcolor, (0,0,width,height),3)
	for i in range(len(data)):
		draw_text(HUDsurface,data[i], (8,i*lineHeight+lineHeight/2), fonts[0],textcolor)
	HUDsurface.blit(pygame.transform.scale2x(tileset[paintNumber]), (width-tileset[paintNumber].get_width()*2-16,lineHeight))

	screen.blit(HUDsurface, (hudx,hudy))
	return HUDsurface
def drawCursor():
	"""Draws the cursor/crosshairs"""
	pygame.draw.aaline(screen, (255,255,10), (inputhandler.mousex-5,inputhandler.mousey-5),(inputhandler.mousex+5,inputhandler.mousey+5))
	pygame.draw.aaline(screen, (255,255,10), (inputhandler.mousex+5,inputhandler.mousey-5),(inputhandler.mousex-5,inputhandler.mousey+5))
	pygame.draw.aaline(screen, (0,0,0), (inputhandler.mousex-5+1,inputhandler.mousey-5),(inputhandler.mousex+5+1,inputhandler.mousey+5))
	pygame.draw.aaline(screen, (0,0,0), (inputhandler.mousex+5+1,inputhandler.mousey-5),(inputhandler.mousex-5+1,inputhandler.mousey+5))
	
def quit():
	screen.fill((250,100,100,100))
	draw_text(screen,"QUITTING", (100,100), fonts[0])
	pygame.display.flip()
	exit()

def nextPaintnumber(paintNumber, length):
	if paintNumber < length-1:
		return paintNumber+1
	else:
		return 0
def previousPaintnumber(paintNumber, length):
	if paintNumber > 0:
		return paintNumber-1
	else:
		return length-1
def fill(tilemap, (x1,y1),(x2,y2),number = 0):
	for i in range(x1,x2):
		for j in range(y1,y2):
			tilemap[i][j] = number
####Initiate pygame stuff
print "Welcome to the Roy tilemap editor! Controls are as follows:"
print " - place tile -- left mouse button"
print " - select tile -- right mouse button"
print " - save -- CTRL+S"
print " - next tile -- E"
print " - previous tile -- Q"
print " - fill with current tile -- CTRL+F"
print " - revert to last save -- CTRL+Z or CTRL+R"
print 

while True:
	try:
		try:
			savemapfile = loadmapfile = sys.argv[1]
		except:
			savemapfile = loadmapfile = raw_input("What map would you like to load?")
		BASEPATH = os.path.abspath(__file__)
		BASEPATH = BASEPATH[:BASEPATH.index('src')]
		path = os.path.join(BASEPATH,'levels',loadmapfile+'.map')
		open(path,'r')
		tilemap = load_tilemap(loadmapfile)
		break
	except IOError:
		if raw_input("That map file doesn't exist yet, would you like to create it?").lower() in ('yes','y','yeah','affirmative','yes please'):
			tilemap = load_tilemap('default')
			break

pygame.init()
windowSize = windowWidth, windowHeight = 400,240
screen = pygame.display.set_mode(windowSize)
pygame.display.set_caption('Tilemap Editor')
screen.fill((200,0,0))
draw_text(screen, "LOADING",('c','c'),pygame.font.Font(None,48),(255,255,255))
pygame.display.flip()
pygame.mouse.set_visible(False)
clock = pygame.time.Clock()
inputhandler = InputHandler()
fonts = []
fonts.append(pygame.font.SysFont('Verdana', 15))
camera = Camera(screen)
HUD =pygame.Surface(HUDSIZE)

tilesetfile = "tileset_1.png"
tileset = load_tileset(tilesetfile)
tileWidth = tileset[0].get_width()
tileHeight = tileset[0].get_height()

windowSize = windowWidth, windowHeight = tileWidth*len(tilemap),tileHeight*len(tilemap[0])
screen = pygame.display.set_mode(windowSize)


paintNumber = 0

while True:
	####KEYBOARD/MOUSE####
	inputhandler.update()
	####PAINTING####
	##Change Current Tile##
	if K_e in inputhandler.keyspressed or inputhandler.mousepressed[4]:
		paintNumber = (paintNumber+1)%len(tileset)
	if K_q in inputhandler.keyspressed or inputhandler.mousepressed[5]:
		paintNumber = (paintNumber-1)%len(tileset)
	elif inputhandler.mousebuttons[RMB]:
		x = int(inputhandler.mousex/float(tileWidth))
		y = int(inputhandler.mousey/float(tileHeight))
		paintNumber = tilemap[x][y]

	####Paint####
	if inputhandler.mousebuttons[LMB] or inputhandler.mousepressed[LMB]:
		x = int(inputhandler.mousex/float(tileWidth))
		y = int(inputhandler.mousey/float(tileHeight))
		tilemap[x][y] = paintNumber
	
	####SPECIAL COMMANDS####
	if inputhandler.keys[K_LCTRL]:
		if K_s in inputhandler.keyspressed:
			print "Saving"
			save_tilemap(tilemap,savemapfile)
		if K_r in inputhandler.keyspressed or K_z in inputhandler.keyspressed:
			print "Reloading map from file"
			tilemap = load_tilemap(loadmapfile)
		if K_f in inputhandler.keyspressed:
			for i in range(len(tilemap)):
				for j in range(len(tilemap[0])):
					tilemap[i][j] = paintNumber

	
	#DRAWING
	draw_tiles(screen,tilemap,tileset)
	drawHUD(HUD,tileset,paintNumber,["Map File: "+loadmapfile,"Tileset: "+tilesetfile,"Size: "+str(len(tilemap))+"x"+str(len(tilemap[0])),"Mouse Position: "+str(int(inputhandler.mousex/tileWidth))+","+str(int(inputhandler.mousey/tileHeight)),"Current Image: "+str(paintNumber+1)+"/"+str(len(tileset))])
	drawCursor()
	pygame.display.flip() #Update the screen
	clock.tick(FPS) #Control framerate
